/*
 * @(#)JobLaunchServlet.java $version 2010. 11. 2.
 *
 */

package com.mywep.myalimi.controller;

import java.io.IOException;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.configuration.JobLocator;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

/**
 * 
 */
public class JobLaunchServlet extends HttpServlet {
	//	private static final Logger LOGGER = LoggerFactory.getLogger(JobLaunchServlet.class);

	private static final long serialVersionUID = 1L;
	private static final String FIRE_TIME_KEY = "schedule.scheduledFireTime";
	private final static Log LOG = LogFactory.getLog(JobLaunchServlet.class);

	@Autowired
	@Qualifier("syncJobLauncher")
	private JobLauncher syncJobLauncher;

	@Autowired
	@Qualifier("jobRegistry")
	private JobLocator jobLocator;

	public void setSyncJobLauncher(JobLauncher syncJobLauncher) {
		this.syncJobLauncher = syncJobLauncher;
	}

	@Override
	public void init() throws ServletException {
		SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

	}

	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ServletOutputStream outStream = response.getOutputStream();
		MDC.put("outputStream", outStream);

		try {
			String jobName = request.getParameter("job");

			Job job = jobLocator.getJob(jobName);

			JobParametersBuilder builder = new JobParametersBuilder();
			builder.addString(jobName, Calendar.getInstance().toString().substring(0, 100));

			JobExecution jobExec;
			jobExec = syncJobLauncher.run(job, builder.toJobParameters());
			String msg = String.format(" Job Execution[ID:%d] finished. ExitStatus is  %s", jobExec.getJobId(), jobExec.getExitStatus().getExitCode());
			IOUtils.write(msg, outStream);
		} catch (Exception e) {
			LOG.error(e);
		} finally {
			MDC.remove("outputStream");
		}
	}

}
